<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="id" prop="fileId">-->
<!--        <el-input-->
<!--          v-model="queryParams.fileId"-->
<!--          placeholder="请输入id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-input
          v-model="queryParams.fileType"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="文件路径" prop="filePath">-->
<!--        <el-input-->
<!--          v-model="queryParams.filePath"-->
<!--          placeholder="请输入文件路径"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间" prop="createtime">
        <el-date-picker clearable
          v-model="queryParams.createtime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建人账号" prop="createby" label-width="100px" >
        <el-input
          v-model="queryParams.createby"
          placeholder="请输入创建人账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:competition:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:competition:question:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="fileId" />-->
      <el-table-column label="文件名称" align="center" prop="fileName" width="600" />
<!--      <el-table-column label="文件路径" align="center" prop="filePath" />-->
<!--      <el-table-column label="文件来源" align="center" prop="fileType" />-->
      <el-table-column label="创建时间" align="center" prop="createtime" width="220">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.createtime, formatTime)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人账号" align="center" prop="createby" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file_info:info:remove']"
          >删除</el-button>
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row.filePath)"
            v-hasPermi="['file_info:info:remove']"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件上传对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="文件名称" prop="fileName">-->
<!--          <el-input v-model="form.fileName" placeholder="请输入文件名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="文件路径" prop="filePath">-->
<!--          <el-input v-model="form.filePath" placeholder="请输入文件路径" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="报名赛事" prop="competitionId">-->
<!--          <el-select v-model="queryParams.competitionId" placeholder="请选择赛事">-->
<!--            <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--          &lt;!&ndash;          <el-input v-model="form.competitionId" placeholder="请输入报名赛事" />&ndash;&gt;-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->


  <!-- 用户导入对话框 -->
  <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="赛事" prop="competitionId">
        <el-select v-model="form.competitionId" placeholder="请选择赛事">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-upload class="upload-demo" :headers="{Authorization: Authorization}"
               :action="uploadUrl" :data="{fileName: fileName,fileUrl:fileUrl}" name="file"
               :on-success="handleSuccess" :show-file-list="true" :file-list="fileList"
               :limit = "1"
               accept=".doc,.docx,.pdf"
               style="text-align:center">
      <el-button size="small" type="primary" plain>上传试题</el-button>
      <div slot="tip" class="el-upload__tip">
        <p style="color: #cb011f">支持格式：.doc .docx .pdf ，文件不能超过20MB且仅能上传1个文件</p>
        <p style="color: #cb011f">试题文件名称建议为: XX年赛事试题,以便后期查找!</p>
      </div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="upload.open = false">取 消</el-button>
    </div>
  </el-dialog>

  </div>
</template>

<script>
import {getInfo, delInfo, addInfo, updateInfo } from "@/api/file_info/info";
import {addExamQuestions, examlistInfo, loadCompetitionQuestion} from "@/api/competitionNEW/competition";
import {getToken} from "@/utils/auth";

export default {
  name: "Info",
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "试题上传",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
      },
      fileList: [],
      Authorization: 'Bearer ' + getToken(),
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/newUpload',
      fileName: "试题附件",
      fileUrl:"/examQuestions",
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      filePaths:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件上传表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        fileName: null,
        filePath: null,
        fileType: null,
        createtime: null,
        createby: null,
        competitionId:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        competitionId: [
          { required: true, message: "赛事不能为空", trigger: "change"}
        ],
      },
    };
  },

  created() {
    this.getList();
    this.loadCompetitionQuestion();
  },
  methods: {
    //成绩附件上传
    handleSuccess(res, file) {
      console.log(res)
      if (res.code == 200) {
        this.fileList.push({
          name: res.originalFilename,
          type: 0,
          url: res.url
        });
      }else {
        this.$message.warning(res.msg);
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
// 提交上传文件
    submitFileForm() {
      if (this.fileList.length>0){
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.url = this.fileList[0].url;
            this.form.name = this.fileList[0].name;
            addExamQuestions(this.form).then(response => {
              this.$modal.msgSuccess("上传成功");
            });
          }
        });
        this.upload.open = false;
        this.fileList=[];
        this.getList();
      }else {
        this.$modal.msgError("请上传报告");
      }
    },
    /**
     * 赛事下拉选加载
     */
    loadCompetitionQuestion() {
      console.log("赛事下拉选加载");
      loadCompetitionQuestion().then(response => {
        this.options = response.data
        console.log(this.options);
      });
    },
    /** 查询文件上传列表 */
    getList() {
      this.loading = true;
      examlistInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        filePath: null,
        fileType: null,
        createtime: null,
        createby: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.names = selection.map(item => item.fileName)
      this.filePaths = selection.map(item => item.filePath)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.loadCompetitionQuestion();
      this.reset();
      this.open = true;
      this.title = "添加文件上传";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getInfo(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件上传";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      const fileNames = row.fileName || this.names;
      this.$modal.confirm('是否确认删除文件名称为"' + fileNames + '"的数据项？').then(function() {
        return delInfo(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('file_info/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
   //文件下载
   //  handleDownload2(row){
   //    download(row).then(response => {
   //        const link = document.createElement('a');
   //        link.href = response.data; // 获取服务器返回的URL
   //        link.download = 'competition_system_file.zip'; // 替换为实际的文件名
   //        link.click();
   //        window.URL.revokeObjectURL(url); // 释放内存
   //      })
   //      .catch(error => {
   //        console.error('下载文件失败:', error);
   //      });
   //    },
    handleDownload(value){
      console.log("###############")
      console.log(value)
      //根据文件路径参数，按斜杠进行分割，取得文件名，这是download函数需要的第三个参数
      let list = value.split("/");
      let fileName = list[list.length-1];
      //这是文件路径参数，因为download函数需要传三个参数，这是第二个参数
      let params = {
        resource:value
      }
      /** request里面的download下载函数 */
      //download函数是若依自带的，第一个参数是请求的url路径，不需要变，这个路径下的controller后台方法也是若依写好封装好了的。
        window.location.href = value;

    },
    },
    // 文件下载处理
    // handleDownload(row) {
    //   const url = row.filePath || this.filePaths;
    //   const name = row.fileName || this.names;
    //   console.log("下载!!!!!!!!!")
    //   console.log(name)
    //   console.log(url)
    //   var suffix = url.substring(url.lastIndexOf("."), url.length);
    //   const a = document.createElement('a')
    //   a.setAttribute('download', name + suffix)
    //   a.setAttribute('target', '_blank')
    //   a.setAttribute('href', url)
    //   a.click()
    // },
};
</script>
